package com.fsl.springbootdesignpattern.d_proxy.CustomProxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author dell
 * 自定义ClassLoader
 */
public class MyClassLoader extends ClassLoader {

    private File file;

    public MyClassLoader() {
        String path = MyClassLoader.class.getResource("").getPath();
        this.file = new File(path);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //通过.class文件，加载.class文件到内存当中并且在JVM当中生成类
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        if(file != null){
            File classFile = new File(file,name.replaceAll("\\.", "/") + ".class");
            if(classFile.exists()){
                FileInputStream fis = null;
                ByteArrayOutputStream out = null;
                try{
                    fis = new FileInputStream(classFile);
                    /*out = new ByteArrayOutputStream();
                    byte [] buff = new byte[1024];
                    int len;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff, 0, len);
                    }*/
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    //调用defineClass方法，将字节数组转换成Class对象
                    return this.defineClass(className, bytes, 0, bytes.length);
                    //return defineClass(className, out.toByteArray(), 0,out.size());
                }catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    if(null != fis){
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(null != out){
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //先不删除，可以看到class文件内容
                    boolean delete = classFile.delete();
                }
            }
        }
        return super.findClass(name);
    }
}
